home | previous topic | next topic

Method Basics


Objectives

ü Understand and use methods as a means of breaking a complex program into manageable pieces.
ü Code programs using methods.
ü Work with instance variables and methods.
ü Use overloaded methods and constructors.
ü Pass objects to and from methods.
ü Comment programs using Javadocs.
ü Understand the scope of variables.

Introduction

Understand and use methods as a means of breaking a complex program into manageable pieces. There are a number of reasons why we do this.
  • methods serve to break up (decompose) a complex problem into manageable pieces
  • methods can be reused in various places in the program by calling the method needed
  • one method can call another method (but methods cannot be nested)

Methods by Any Other Name

Methods are used in most other programming languages but may be called different things. Some of the more common names for methods are:
  • method
  • subroutine
  • function
  • procedure
  • pre-defined process

Method Design

There are rules and strategies for how to decompose your code most effectively. We’ll take a look at this towards the end of the topic. First, we’ll start with the syntax of methods.

This is a method.

Syntax:
modifier(s) returnValueType methodName(parameterList)
{
body
}

Example:
UnLabelledMethod.PNG

Labeled Example:
LabelledMethod.PNG